package com.fzu.ess.common.service.Impl;

import com.fzu.ess.common.Const;
import com.fzu.ess.common.service.ImageService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;


/**
 * Created by ercha on 2015/10/28.
 */
@Service
public class ImageServiceImpl implements ImageService {
    public void getImage(String filename, String extension,
                                   HttpServletResponse response){
        String path = getPath(filename);

        FileInputStream fis = null;
        response.setContentType("image/gif");
        try {
            OutputStream out = response.getOutputStream();
            File file = new File(path + filename + "." + extension);
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean deleteFromDisk(String filename) {
        if(filename==null || filename.length()<1){
            return true;
        }

        if(filename.charAt(0) == '@'){
            filename = filename.substring(2);
        }

        try {
            //获取路径
            String path = getPath(filename);

            int res = 0;
            for(int i=0; i<3; ++i){
                File f = new File(path + Const.IMAGE_PREFIX[i] + filename);
                res += f.delete() ? 1 : 0;
            }
            File f = new File(path + filename);
            res += f.delete() ? 1 : 0;
            return res == 4;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    private String getPath(String filename){
        String s = File.separator;

        int si = 0;
        if(filename.charAt(0) == '@'){
            si = 2;
        }
        String path = System.getProperty("user.home") + s + Const.IMAGE_PATH;
        path += filename.substring(si, si+4) + s;
        si += 4;
        path += filename.substring(si, si+2) + s;
        si += 2;
        path += filename.substring(si, si+2) + s;
        return path;
    }
}


